package com.nurt.dao.impl;

import java.sql.*;

import com.nurt.dao.UserDao;
import com.nurt.entity.UserEntity;
import com.nurt.utils.DatabaseManager;

public class UserDaoImpl implements UserDao{
    private Connection conn;

    public UserDaoImpl() {
        try {
            this.conn = DatabaseManager.getInstance().getConnection();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public UserEntity selectUser(int id) throws SQLException {
        String sql = "SELECT * FROM users WHERE id = " + id;
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            UserEntity user = new UserEntity();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            return user;
        } else {
            return null;
        }
    }

    public UserEntity selectUser(UserEntity user) throws SQLException {
        String sql = "SELECT * FROM users WHERE username = '" + user.getUsername() + "' AND password = '" + user.getPassword() + "'";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            UserEntity foundUser = new UserEntity();
            foundUser.setId(rs.getInt("id"));
            foundUser.setUsername(rs.getString("username"));
            foundUser.setPassword(rs.getString("password"));
            return foundUser;
        } else {
            return null;
        }
    }

    public int updateUser(UserEntity user) throws SQLException {
        String sql = "UPDATE users SET username = '" + user.getUsername() + "', password = '" + user.getPassword() + "' WHERE id = " + user.getId();
        Statement stmt = conn.createStatement();
        return stmt.executeUpdate(sql);
    }

    public int insertUser(UserEntity user) throws SQLException {
        String sql = "INSERT INTO users (username, password) VALUES ('" + user.getUsername() + "', '" + user.getPassword() + "')";
        Statement stmt = conn.createStatement();
        stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            return rs.getInt(1);
        } else {
            throw new SQLException("Creating user failed, no ID obtained.");
        }
    }
}